package com.godyao.aop;

import com.godyao.response.CommonMessage;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author godyao
 * @date 2022/3/5
 */
@RestControllerAdvice
public class ShortUrlExceptionHandler {
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public CommonMessage handleBindException(Exception e) {
        StringBuilder sb = new StringBuilder();
        String msg = "";
        if (e instanceof BindException) {
            List<FieldError> allErrors = ((BindException) e).getFieldErrors();
            for (FieldError errorMessage : allErrors) {
                sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
            }
            /// MethodArgumentNotValidException
        } else if (e instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            // getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
            List<FieldError> allErrors = bindingResult.getFieldErrors();
            for (FieldError errorMessage : allErrors) {
                sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
            }
            /// ValidationException 的子类异常ConstraintViolationException
        } else if (e instanceof ConstraintViolationException) {
            /*
             * ConstraintViolationException的e.getMessage()形如
             *     {方法名}.{参数名}: {message}
             *  这里只需要取后面的message即可
             */
            msg = e.getMessage();
            if (msg != null) {
                int lastIndex = msg.lastIndexOf(':');
                if (lastIndex >= 0) {
                    msg = msg.substring(lastIndex + 1).trim();
                }
            }
            sb.append(msg);
            /// ValidationException 的其它子类异常
        } else {
            sb.append("处理参数时异常");
        }
        return new CommonMessage(1, sb.toString());
    }
    @ExceptionHandler(Exception.class)
    public CommonMessage exceptionHandler (Exception e) {
       return new CommonMessage(1, e.getMessage());
    }
}
